<!--
 * @description: 
 * @Author: lhr
 * @Date: 2020-10-26 13:39:03
 * @LastEditors: lhr
 * @LastEditTime: 2020-10-30 16:51:27
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      iframe {
        height: 0;
        width: 0;
        border: none;
        opacity: 0;
      }
      p {
        margin: 30px 0 10px 0;
      }
      button {
        border: 1px solid #59aaec;
        padding: 5px;
        background: #fff;
        border-radius: 5px;
        color: #59aaec;
      }

      input[type="text"],
      input[type="password"] {
        height: 30px;
        line-height: 30px;
        border-radius: 5px;
        border: 1px solid #aaa;
        padding: 0 5px;
      }
    </style>

    <script>
      function fileUploadFn() {
        let preDoc = document
          .getElementsByTagName("iframe")[4]
          .contentDocument.body.getElementsByTagName("pre")[0];
        try {
          var result = JSON.parse(preDoc ? preDoc.innerHTML : "{}");
          console.log(result);
        } catch (e) {
          console.log(e);
        }
      }
    </script>
  </head>
  <body>
    <p>post application/x-www-form-urlencoded</p>
    <form name="uploadForm" target="ifr1" method="post" action="login.do">
      <input name="username" />
      <input type="password" name="password" />
      <button type="submit">提交</button>
    </form>
    <iframe name="ifr1" title=""></iframe>

    <p>post text/plain</p>
    <form
      name="uploadForm2"
      target="ifr2"
      method="post"
      enctype="text/plain"
      action="login.do"
    >
      <input name="username" />
      <input type="password" name="password" />
      <button type="submit">提交</button>
    </form>
    <iframe name="ifr2" title=""></iframe>

    <p>post multipart/form-data</p>
    <form
      name="uploadForm3"
      target="ifr3"
      method="post"
      enctype="multipart/form-data"
      action="login.do"
    >
      <input name="username" />
      <input type="password" name="password" />
      <button type="submit">提交</button>
    </form>
    <iframe name="ifr3" title=""></iframe>

    <p>get</p>
    <form name="uploadForm4" target="ifr4" action="login.do">
      <input name="username" />
      <input type="password" name="password" />
      <button type="submit">提交</button>
    </form>
    <iframe name="ifr4" title=""></iframe>

    <p>文件上传：form 的 input[file]+iframe</p>
    <form
      name="uploadForm5"
      target="ifr5"
      method="post"
      enctype="multipart/form-data"
      action="https://11.12.108.22:8443/upload?userid=5379a67acdb4cb3b&ts=1603693878227&sign=b89d58acd95d0f5b12f4e835dadb223c607e45ba"
    >
      <input name="perm" value="1" />
      <input name="photo" type="file" />
      <button type="submit">提交</button>
    </form>
    <iframe name="ifr5" onload="fileUploadFn()" title=""></iframe>

    <p>文件上传：input[file]+formData</p>
    <input id="perm5" value="1" />
    <input type="file" id="file5" />
    <button type="button" onclick="fileUploadFormData()">xhr提交</button>
    <button type="button" onclick="fileUploadFormData2()">fetch提交</button>

    <script>
      function fileUploadFormData() {
        var file = document.getElementById("file5").files[0];
        var formData = new FormData();
        formData.append("perm", document.getElementById("perm5").value);
        formData.append("file", file);
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              console.log(xhr.response);
            } else {
              console.log("!ok", xhr.status, xhr.statusText);
              console.log(xhr.response);
            }
          }
        };
        xhr.open("post", "http://localhost:3000/login0", true);
        xhr.responseType = "json";
        xhr.send(formData);
      }

      // fetch　实现
      function fileUploadFormData2() {
        var file = document.getElementById("file5").files[0]; // 获取文件
        var formData = new FormData(); // 创建formData数据格式
        formData.append("perm", document.getElementById("perm5").value); // 添加需要提交的数据
        formData.append("file", file);
        fetch("http://localhost:3000/login0", {
          method: "POST",
          headers: {
            "Content-Type": "multripart/form-data",
          },
          body: formData,
        })
          .then(function (res) {
            if (res.ok) {
              return res.json();
            }
            throw new Error(res);
          })
          .then((myJson) => {
            console.log(myJson);
          })
          .catch((err) => {
            console.log("!ok", err);
          });
      }
    </script>

    <p>文件上传：分片上传</p>
    <input id="perm6" value="1" />
    <input type="file" id="file6" />
    <button type="button" onclick="fileUploadTrunk()">xhr提交</button>
    <button type="button" onclick="fileUploadTrunk2()">fetch提交</button>
    <script>
      function fileUploadTrunk() {
        try {
          var file = document.getElementById("file6").files[0];
          var size = 1024; // 每兆一个单位
          var len = Math.ceil(file.size / size);
          trunkUpload(0, size);

          var fileId = "";
          function trunkUpload(index) {
            var blob = file.slice(index * size, (index + 1) * size);
            var formData = new FormData();
            formData.append("perm", document.getElementById("perm5").value);
            formData.append("blob", blob);
            formData.append("filename", file.name);
            formData.append("filesize", blob.size);
            if (fileId) {
              formData.append("fileid", fileId);
            }
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                  if (index + 1 === len) {
                    fileId = "";
                    console.log("上传完成: ", xhr.response.fileid);
                  } else {
                    fileId = fileId || xhr.response.fileid;
                    trunkUpload(index + 1);
                  }
                } else {
                  console.log("!ok", xhr.status, xhr.statusText);
                  console.log(xhr.response);
                }
              }
            };
            xhr.open("post", "http://localhost:3000/trunkUpload", true);
            xhr.responseType = "json";
            xhr.send(formData);
          }
        } catch (e) {
          console.log(e);
        }
      }

      function fileUploadTrunk2() {
        try {
          var file = document.getElementById("file6").files[0];
          var size = 1024; // 每兆一个单位
          var len = Math.ceil(file.size / size);
          trunkUpload(0, size);

          var fileId = "";
          function trunkUpload(index) {
            var blob = file.slice(index * size, (index + 1) * size);
            var formData = new FormData();
            formData.append("perm", document.getElementById("perm5").value);
            formData.append("blob", blob);
            formData.append("filename", file.name);
            formData.append("filesize", blob.size);
            if (fileId) {
              formData.append("fileid", fileId);
            }
            fetch("http://localhost:3000/trunkUpload", {
              method: "POST",
              headers: {
                "Content-Type": "multripart/form-data",
              },
              body: formData,
            })
              .then(function (res) {
                if (res.ok) {
                  return res.json();
                }
                throw new Error(res);
              })
              .then((myJson) => {
                console.log(myJson);

                if (index + 1 === len) {
                  fileId = "";
                  console.log("上传完成: ", myJson.fileid);
                } else {
                  fileId = fileId || myJson.fileid;
                  trunkUpload(index + 1);
                }
              })
              .catch((err) => {
                console.log("!ok", err);
              });
          }
        } catch (e) {
          console.log(e);
        }
      }
    </script>

    <p>文件上传：带进度条(Fetch不支持)</p>
    <input id="perm7" value="1" />
    <input type="file" id="file7" />
    <progress min="0" max="100" value="0">0% complete</progress>
    <button type="button" onclick="fileUploadProgress()">提交</button>

    <script>
      function fileUploadProgress() {
        var file = document.getElementById("file7").files[0]; // 获取文件
        var formData = new FormData(); // 创建formData数据格式
        formData.append("perm", document.getElementById("perm7").value); // 添加需要提交的数据
        formData.append("file", file);
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              console.log(xhr.response);
            } else {
              console.log("!ok", xhr.status, xhr.statusText);
              console.log(xhr.response);
            }
          }
        };
        xhr.open("post", "http://localhost:3000/login0", true);
        var progressBar = document.querySelector("progress");
        xhr.upload.onprogress = function (e) {
          var num = (e.loaded / e.total) * 100;
          progressBar.value = num;
          progressBar.textContent = num;
        };
        xhr.upload.onloadstart = function (e) {
          console.log("onloadstart");
        };
        xhr.upload.onloadend = function (e) {
          console.log("loadend");
        };
        xhr.upload.onload = function (e) {
          console.log("load");
        };
        xhr.responseType = "json";
        xhr.send(formData);
      }
    </script>
  </body>
</html>
